package com.example.login.vm

import androidx.lifecycle.viewModelScope
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.example.base.app.RouterPath
import com.example.common.vm.BaseViewModel
import com.example.login.intent.AccountViewIntent
import com.example.login.repo.AccountRepository

import com.example.login.state.AccountUiState
import com.tencent.mmkv.MMKV
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject

@HiltViewModel
class AccountViewModel : BaseViewModel<AccountViewIntent>() {
    private val repository: AccountRepository = AccountRepository()
    private val _uiStateFlow = MutableSharedFlow<AccountUiState>()

    val uiStateFlow : SharedFlow<AccountUiState> = _uiStateFlow.asSharedFlow()
    private val _uiState = MutableStateFlow<AccountUiState>(AccountUiState.EmptyState)
    val uiState: StateFlow<AccountUiState> = _uiState.asStateFlow()

    override fun dispatchIntent(intent: AccountViewIntent) {
        when(intent){
            is AccountViewIntent.LoginToServer -> loginToServer(intent.userName, intent.password)
            is AccountViewIntent.RegisterToServer -> registerToServer(intent.userName, intent.password)
        }
    }

    private fun loginToServer(userName: String, password: String) {
        mViewModelScope.launch(mDispatcher) {
            ToastUtils.showLong("登录成功")
            ARouter.getInstance().build(RouterPath.PATH_MAIN_ACTIVITY).navigation()
            _uiState.value = AccountUiState.RegisterToServerSuccess(repository.loginToServer(userName, password).data)
        }
    }



    private fun registerToServer(userName: String, password: String) {
        mViewModelScope.launch(mDispatcher) {
            ToastUtils.showLong("注册成功")
            ARouter.getInstance().build(RouterPath.PATH_LOGIN_PAGE).navigation()
            _uiState.value = AccountUiState.RegisterToServerSuccess(repository.registerToServer(userName, password).data)
        }
    }





}